import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import Taro, { FC, useRouter, useShareAppMessage } from '@tarojs/taro'
import { View, Text, Image, Swiper, SwiperItem, ITouchEvent } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import { Subscription } from 'rxjs';

import Login from '@/components/loginPopup/index'
import { useRoomDataFacade } from '@/hooks/useRoomDataFacade'
import { HomePageListRsp, LiveContent } from '@/models/response/roomRsp'

import '@@/app_style'
import "taro-ui/dist/style/components/button.scss" // 按需引入
import "taro-ui/dist/style/components/tab-bar.scss";
import "taro-ui/dist/style/components/badge.scss";
import './index.scss'


export const Index: FC = () => {
  //导入门面的所有元素作为页面绑定
  const [roomFacade] = useRoomDataFacade();

  const [homeList, setHomeList] = useState({} as HomePageListRsp)

  //登录弹窗组件相关状态
  const [clicked, setClicked] = useState(false);
  //跳转url
  const [goUrl, setGoUrl] = useState('');

  //分享卡片进来的路径必带下面两个参数，扫码进入的只带上面的scene参数
  const router = useRouter();
  const roomIdRef = useRef(router.params.roomId || "");
  const refIdref = useRef(router.params.refId || ""); // 小程序码带的id

  // 如果通过小卡片，跳转到详情页
  useLayoutEffect(() => {
    if (!!roomIdRef.current || !!refIdref.current) {
      Taro.navigateTo({
        url: `/pages/liveRoom/LiveDetails/index?roomId=${roomIdRef.current}&refId=${refIdref.current}`,
      })
      console.log('useLayoutEffect', roomIdRef.current);
    }
  }, [roomIdRef.current, refIdref.current])

  //跳转编辑页
  const toCreateLive = () => {
    setGoUrl("/pages/liveRoom/createLive/index");
    setClicked(true);
  }

  const data = [
    {
      title: '特点一',
      Image: ASSETS_PATH + '/index_first.png',
      content: '内容安全',
      describe: '全方位直播安全护航'
    },
    {
      title: '特点二',
      Image: ASSETS_PATH + '/index_first.png',
      content: '灵活开播',
      describe: '支持多端多种直播和观看方式'
    },
    {
      title: '特点三',
      Image: ASSETS_PATH + '/index_first.png',
      content: '流量闭环',
      describe: '支持导入流量到私域平台'
    },
  ]


  // 转发分享
  useShareAppMessage(res => {
    if (res.from === 'button') {
      // console.log(res, '按钮属性')
    }
    return {
      title: ``,
      imageUrl: '',
      path: `/pages/index/index`,

    }
  })

  //第一个useEffect，不需要监听任何值，只执行一次
  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      roomFacade.getMain()
        .subscribe(
          (res: HomePageListRsp) => {
            setHomeList(res);
          }
        )
    ];
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, []);

  const toDetails = (roomId: string, e: ITouchEvent) => {
    e.stopPropagation();

    Taro.navigateTo({
      url: `/pages/liveRoom/LiveDetails/index?roomId=${roomId}`
    })
  }

  return (
    <View className='index' >
      {/* 主体内容部分 */}
      {/* <ScrollView> */}
      <View className='main'>
        {/* 头部背景图*/}
        <View className='top'></View>
        <View className='content'>
          <Swiper className='test-h' indicatorColor='#E6E6E6' indicatorActiveColor={MAIN_COLOR} circular indicatorDots autoplay >
            {
              data.map((item, index) => (
                <SwiperItem key={String(index)} className='content_item'  >
                  <View className='box1-top'>
                    <Text className='title' >{item.title}</Text>
                  </View>
                  <View className='box1-ct'>
                    <Image src={item.Image} className='box1-img'></Image>
                  </View>
                  <View className='ct'>{item.content}</View>
                  <View className='describe' >{item.describe}</View>
                </SwiperItem>
              ))
            }
          </Swiper>
        </View>
        {/* <View className='content'>
          <Swiper
            className='test-h'
            indicatorColor='#E6E6E6'
            indicatorActiveColor='#D20202'
            circular
            indicatorDots
            autoplay
          >
            {
              homeList.secondFloor && homeList.secondFloor.length >= 3 && homeList.secondFloor.map((item, index) => (
                <SwiperItem key={String(index)} className='content_item' onClick={(e) => toDetails(item.roomId, e)}>
                  <View className='box1-top'>
                    <Text className='title'>{item.roomName}</Text>
                  </View>
                  <View className='box1-bt'>
                    <View className='bt-left'>
                      <View className='time'> 回放时间：{formatTime(item.startTime)} </View>
                    </View>
                    <View className='status' onClick={(e) => toDetails(item.roomId, e)}>{item.status == ROOM_STATUS.ENDED ? '已结束' : ''}</View>
                  </View>
                </SwiperItem>
              ))
            }
          </Swiper>
        </View> */}
        {/* 精彩内容 */}
        {
          homeList.thirdFloor && homeList.thirdFloor.map((item: LiveContent, index) => (
            <View className='box2' key={index} >
              <View className='text'>精彩内容</View>
              <Swiper className='box2_item' displayMultipleItems={homeList.thirdFloor.length > 3 ? 3.2 : homeList.thirdFloor.length} >
                <SwiperItem>
                  <View className='box'>
                    <View className='ct_img' onClick={(e) => toDetails(item.roomId, e)}>
                      <Image className='img' src={item.picUrl} ></Image>
                    </View>
                    <View className='text1'>{item.roomName}</View>
                  </View>
                </SwiperItem>
              </Swiper>
            </View>
          ))
        }
        <AtButton className='bt' onClick={toCreateLive}>
          <View className='bt-box'>
            <View className='text2'>开始直播</View>
            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='playImg'></Image>
          </View>
        </AtButton>
      </View>

      <Login goUrl={goUrl} setGoUrl={setGoUrl} clicked={clicked} setClicked={setClicked} />
    </View >
  )
}

export default Index